package iconsul

import (
	"fmt"
	"gitee.com/tietang/terrace-go/v2/base"
	"gitee.com/tietang/terrace-go/v2/base/starter/iiris"
	"github.com/hashicorp/consul/api"
	"github.com/kataras/iris/v12"
	log "github.com/sirupsen/logrus"
	"github.com/tietang/go-utils"
	"github.com/tietang/props/v3/kvs"
)

var consulClient *api.Client

func ConsulClient() *api.Client {
	base.Check(consulClient)
	return consulClient
}

type ConsulStarter struct {
	base.BaseStarter
	client       *api.Client
	serviceId    string
	registration *api.AgentServiceRegistration
}

func (s *ConsulStarter) Init(ctx base.StarterContext) {
	config := api.DefaultConfig()
	config.Address = "172.16.1.248:8500"
	var err error
	s.client, err = api.NewClient(config)
	if err != nil {
		log.Fatal("consul client error : ", err)
	}
	addr, err := utils.GetExternalIP()
	port := ctx.Props().GetIntDefault("app.server.port", 8080)
	name := ctx.Props().GetDefault("app.name", "unknowname")
	s.serviceId = fmt.Sprintf("%s:%s:%d", name, addr, port)
	s.registration = new(api.AgentServiceRegistration)
	s.registration.ID = s.serviceId
	s.registration.Name = name
	s.registration.Port = port
	s.registration.Tags = []string{"serverNode"}
	s.registration.Address = addr
	check := &api.AgentServiceCheck{}
	err = kvs.Unmarshal(ctx.Props(), check, "consul.discovery.check")
	if err != nil {
		log.Fatal("unmarshal consul check config error : ", err)
	}
	checkUrl := ctx.Props().GetDefault("consul.discovery.check.checkUrl", "/check")
	check.HTTP = fmt.Sprintf("http://%s:%d%s", s.registration.Address, s.registration.Port, checkUrl)
	s.registration.Check = check

}
func (s *ConsulStarter) Setup(ctx base.StarterContext) {
	iiris.Iris().Get("/check", func(context iris.Context) {
		context.WriteString("ok!")
	})
}
func (s *ConsulStarter) Start(ctx base.StarterContext) {
	err := s.client.Agent().ServiceRegister(s.registration)
	log.Info("Register Service: ", s.serviceId)
	if err != nil {
		log.Fatal("register server error : ", err)
	}
}
func (s *ConsulStarter) Stop(ctx base.StarterContext) {
	err := s.client.Agent().ServiceDeregister(s.serviceId)
	if err != nil {
		log.Fatal("register server error : ", err)
	}
}
